<?php
namespace control;

/*
*运费调整
*/
class freightChangeClass extends adIndexClass
{

    private const title            = '运费调整申请';
    private const page             = 'freightChange';
    private const table            = 'freight_change';
    private const tableKehu        = 'kehu';
    private const tableMaterial    = 'material';

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'orderNo'  => [
                'name'  => "单据编码",
                'width' => 150,
            ],
            'companyOrderNo'  => [
                'name'  => '客户编码',
                'width' => 120,
            ],
            'companyName' => [
                'name'  => "客户名称",
                'width' => 150,
            ],
            'freight'          => [
                'name'  => '原运费('. static::$unit . ')',
                'width' => 150,
            ],
            'newFreight'          => [
                'name'  => '调整运费('. static::$unit . ')',
                'width' => 150,
            ],
            'stid'          => [
                'name'  => '申请人',
                'width' => 150,
            ],
            'freightId'          => [
                'name'  => '关联单据',
                'width' => 150,
            ]
        ];
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户编码"   => text(array("name" => "orderNo")),
                    "客户名称"   => text(array("name" => "companyName")),
                ],
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'coid' => self::$coid,
        ];
        // 客户搜索
        if ($this->post('orderNo') || $this->post('companyName')) {
            $kWhere = search([
                "="    => $equal,
                "like" => [
                    'orderNo'     => $this->post('orderNo'),
                    'companyName' => $this->post('companyName'),
                ],
            ]);
            $where  .= " AND `khid` IN (SELECT khid FROM `kehu` WHERE 1=1 $kWhere)  ";
        }
        //生成查询语句
        $where                       .= search([
            "=" => $equal,
        ]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page                        = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box"  => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $kehu     = query(self::tableKehu, " khid = '$array[khid]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'companyOrderNo':
                        $row[] = $kehu['orderNo'];
                        break;
                    case 'companyName':
                        $row[] = $kehu[$key];
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case 'freightId':
                        $sale_send_order_car = query('sale_send_order_car',"id = '$array[freightId]'");
                        $row[] = $sale_send_order_car['orderNo'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . $this->js() . clear;
        return json_encode($json, 320);
    }

    public function js()
    {
        return <<<eof
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
       $('#freightChangeAddMx').hide()
       $("#freight").html(res.data.freight);
       $("[name='freightId']").val(res.data.freightId);
    },'json');
}
function countPrice(e){
    let agreedPrice = Number($("[name='agreedPrice']").val());
    let agreedDiscount = Number($("[name='agreedDiscount']").val())/100;
    $("#dealPrice").html((agreedPrice*agreedDiscount).toFixed(2))
}
</script>
eof;
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "单据日期：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                ],
                [
                    must . "客户：" => clientProfileClass::kehuSelect(array('value' => $info['khid'])),
                ],
                [
                    must . "原运费：" => "<span id='freight' class='exceed-ellipsis' style='max-width: 90%;'>$info[freight]</span>&nbsp;<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addMx',{})\">选择</span>" . hidden(array('name' => 'freightId', 'value' => $info['freightId'])),
                ],
                [
                    must . "调整运费：" => text(["name" => "newFreight", 'class' => 'text', "value" => $info['newFreight']]),
                ],
                [
                    "备注：" => text(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ],
            ]
        ]);
        return $this->layer(array("title" => "编辑", "height" => 350, "width" => 900, "html" => $html));
    }

    public function editEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            "recordDate"            => $this->post('recordDate'),
            "khid"            => $this->post('khid'),
            "freightId"   => $this->post('freightId'),
            "newFreight"     => $this->post('newFreight')?self::formattingFigure($this->post('newFreight'),'pricePrecision'):0,
            'updateTime' => $this->time
        ];
        $annotation = [
            'khid'          => '客户',
            'freightId' => '原运费',
            'newFreight' => '调整运费',
            'recordDate' => '单据日期',
        ];
        $rules      = [
            'khid'          => 'required',
            'freightId' => 'required',
            'newFreight' => 'required',
            'recordDate' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        $sale_send_order_car = query('sale_send_order_car',"id = '$field[freightId]'");
        $field['freight'] = $sale_send_order_car['freight'];
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array(
                'table' => self::table,
                'where' => "freightId = '$field[freightId]' and khid = '$field[khid]' and coid = '" . self::$coid . "'  and id !='$id'"
            )) > 0) {
            $json['warn'] = '此客户已调整过运费';
        } else {
            if (!$info['id']) {
                $orderNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'YFTZ' . date('Ymd', strtotime($field['recordDate'])),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " and coid = '" . self::$coid . "'",
                ], $field);
                $field        = array_merge($field, [
                    'id'   => $id,
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                    'orderNo' => $orderNo,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "where" => $where,
                    "field" => $field,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = '执行此操作将会永久删除所选的信息,删除后将无法找回，您确定要这么做吗？';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * @return bool|string
     */
    public function addMx()
    {
        $html   =
            materialClass::typeSelect(name: 'type').
            text(array("name" => "car_no", "title" => "车牌号")) .
            text(array("name" => "model", "title" => "规格型号")) .
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "zindex" => 3, "html" => $html, "button" => $button));
    }

    /**
     *添加运费
     */
    public function addMxSearch()
    {
        $like        = [
            'car_no'          => $this->post('car_no'),
            'model'            => $this->post('model'),
        ];
        $equal       = [
            'coid'   => self::$coid,
            'pay_freight'  => 0,
        ];
        $where       = search(["like" => $like, "=" => $equal]);
        $page        = $this->page([
            "table"   => "sale_send_order_car",
            "field"   => "*",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "`time` ASC",
        ]);
        //获取表头
        $tr[]     = ['', '车牌号', '规格型号', '运费', '驾驶员'];
        //获取记录
        foreach ($page['array'] as $array) {
            $checkBox = "<input name='mxId' value='$array[id]' type='radio'>";
            $tr[]     = array(
                $checkBox,
                $array['car_no'],
                $array['model'],
                $array['freight'],
                $array['driver']
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxId = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxId)) {
            $json['warn'] = '请选择产品';
        } else {
            $material = query('sale_send_order_car',"id = '$mxId'");
            $json['data'] = [
                'freightId' => $material['id'],
                'freight'=> self::lostZero($material['freight'],'pricePrecision')
            ];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

}